package org.jeecg.modules.netty.handler.v4;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.netty.protocol.v4.DataFrame;
import org.jeecg.modules.netty.protocol.v4.DataFrameUtil;

import java.util.List;

@Slf4j
public class ByteToDataFrameDecoder extends ReplayingDecoder{


    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        DataFrame frame = new DataFrame();
        frame.setMagic(byteBuf.readUnsignedShort());
        frame.setPlayloadlen(byteBuf.readUnsignedShort());
        frame.setVerion(byteBuf.readByte());
        frame.setEnctype(byteBuf.readByte());
        frame.setType(byteBuf.readByte());
        frame.setReserved(byteBuf.readByte());
        frame.setCrc(byteBuf.readUnsignedShort());
        byte[] playload = new byte[frame.getPlayloadlen()];
        byteBuf.readBytes(playload);
        String playloadStr = new String(playload, DataFrameUtil.CHARSET);
        frame.setPlayload(playloadStr);
        list.add(frame);
        log.info("ByteToLampFrameDecoder.decode() is Complete!");
    }
}
